<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>历史天气数据</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.2/dist/echarts.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/dayjs@1.11.3/dayjs.min.js"></script>
    <style>
        :root {
            --primary-light: #a8d8ea; /* 浅蓝色 */
            --primary-medium: #78c4d4; /* 中等蓝色 */
            --accent-light: #f9c5d1; /* 浅粉色 */
            --accent-medium: #f2789f; /* 中等粉色 */
            --light-bg: #f8f9fa;
            --card-bg: rgba(255, 255, 255, 0.92);
            --text-dark: #37474F;
            --text-light: #78909C;
            --card-shadow: 0 5px 15px rgba(0,0,0,0.05);
        }

        body {
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            min-height: 100vh;
            padding: 20px;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        .chart-container {
            background: var(--card-bg);
            border-radius: 10px;
            box-shadow: var(--card-shadow);
            padding: 20px;
            margin-bottom: 20px;
        }
        .chart-title {
            text-align: center;
            margin-bottom: 20px;
            color: var(--text-dark);
        }
        #temp-trend-chart, #humidity-trend-chart {
            height: 400px;
            width: 100%;
        }
        .back-button {
            text-align: center;
            margin-top: 20px;
        }
        .city-selector {
            margin-bottom: 20px;
            text-align: center;
        }
        .city-selector select {
            width: 200px;
            margin: 0 auto;
        }
        .crawl-section {
            text-align: center;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1 class="text-center my-4">历史天气数据</h1>

        <div class="city-selector">
            <select class="form-select" id="city-select">
                <option value="Beijing">北京</option>
                <option value="Shanghai">上海</option>
                <option value="Guangzhou">广州</option>
                <option value="Shenzhen">深圳</option>
            </select>
        </div>

        <div class="crawl-section">
            <button id="crawl-btn" class="btn btn-primary">
                <i class="bi bi-cloud-download me-2"></i> 采集当前城市数据
            </button>
            <div class="alert mt-3" id="crawl-status" style="display:none;">
                <i class="bi me-2" id="status-icon"></i>
                <span id="crawl-message"></span>
            </div>
        </div>

        <div class="chart-container">
            <h2 class="chart-title">温度变化趋势</h2>
            <div id="temp-trend-chart"></div>
        </div>

        <div class="chart-container">
            <h2 class="chart-title">湿度变化趋势</h2>
            <div id="humidity-trend-chart"></div>
        </div>

        <div class="back-button">
            <a href="/api/weather/home" class="btn btn-primary">
                <i class="bi bi-arrow-left me-2"></i> 返回首页
            </a>
        </div>
    </div>

    <script>
        // 初始化图表
        const tempChart = echarts.init(document.getElementById('temp-trend-chart'));
        const humidityChart = echarts.init(document.getElementById('humidity-trend-chart'));

        // 初始加载数据
        loadCityData('Beijing');

        // 城市选择变化事件
        document.getElementById('city-select').addEventListener('change', function() {
            loadCityData(this.value);
        });

        // 采集按钮事件
        document.getElementById('crawl-btn').addEventListener('click', function() {
            const city = document.getElementById('city-select').value;
            const button = this;
            const statusEl = document.getElementById('crawl-status');
            const messageEl = document.getElementById('crawl-message');
            const iconEl = document.getElementById('status-icon');

            // 保存原始按钮状态
            const originalText = button.innerHTML;

            // 更新按钮状态
            button.innerHTML = '<i class="bi bi-hourglass-split me-2"></i> 采集中...';
            button.disabled = true;
            statusEl.style.display = 'none';

            fetch(`/api/weather/crawl/${city}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应错误');
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('采集结果:', data);

                    if (data.status === 'success') {
                        // 重定向到数据采集结果页面
                        window.location.href = `/api/weather/data_collection_result?city=${city}&status=success&temperature=${data.temperature}&humidity=${data.humidity}&wind_speed=${data.wind_speed}&time_cost=${data.time_cost}`;
                    } else {
                        iconEl.className = 'bi bi-exclamation-triangle-fill text-danger';
                        statusEl.className = 'alert alert-danger mt-3';
                        messageEl.innerHTML = `<strong>${city}数据采集失败！</strong> ${data.reason || '未知错误'}`;
                        statusEl.style.display = 'block';
                    }
                })
                .catch(error => {
                    console.error('采集请求失败:', error);
                    iconEl.className = 'bi bi-exclamation-triangle-fill text-danger';
                    statusEl.className = 'alert alert-danger mt-3';
                    messageEl.innerHTML = `<strong>采集请求失败！</strong> ${error.message || '网络错误'}`;
                    statusEl.style.display = 'block';
                })
                .finally(() => {
                    // 恢复按钮状态
                    button.innerHTML = originalText;
                    button.disabled = false;
                });
        });

        // 加载城市数据函数
        function loadCityData(city) {
            // 显示加载状态
            tempChart.showLoading('default', {
                text: '加载数据中...',
                color: '#78c4d4',
                textColor: '#000',
                maskColor: 'rgba(255, 255, 255, 0.8)'
            });

            humidityChart.showLoading('default', {
                text: '加载数据中...',
                color: '#f2789f',
                textColor: '#000',
                maskColor: 'rgba(255, 255, 255, 0.8)'
            });

            // 发送API请求
            fetch(`/visualization/api/historical_data/${city}?days=30`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`网络响应错误: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('获取到的数据:', data);

                    // 检查数据格式
                    if (!Array.isArray(data)) {
                        throw new Error('无效的数据格式: 预期为数组');
                    }

                    if (data.length === 0) {
                        throw new Error('没有找到历史数据');
                    }

                    // 提取日期和时间
                    const dateTimes = data.map(item => item.date + ' ' + item.time);
                    const temperatures = data.map(item => item.temperature);
                    const humidities = data.map(item => item.humidity);

                    // 设置温度图表
                    tempChart.setOption({
                        title: { text: `${city} - 温度变化趋势 (°C)` },
                        tooltip: {
                            trigger: 'axis',
                            formatter: function(params) {
                                const item = data[params[0].dataIndex];
                                return `
                                    ${item.date} ${item.time}<br/>
                                    温度: ${item.temperature}°C<br/>
                                    湿度: ${item.humidity}%<br/>
                                    风速: ${item.wind_speed}m/s
                                `;
                            }
                        },
                        grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
                        xAxis: {
                            type: 'category',
                            data: dateTimes,
                            axisLabel: {
                                rotate: 45,
                                formatter: function(value) {
                                    return value.split(' ')[0];
                                }
                            }
                        },
                        yAxis: { type: 'value', name: '温度 (°C)' },
                        series: [{
                            name: '温度',
                            type: 'line',
                            data: temperatures,
                            smooth: true,
                            symbol: 'circle',
                            symbolSize: 8,
                            lineStyle: { width: 3, color: '#78c4d4' },
                            itemStyle: { color: '#78c4d4' },
                            areaStyle: {
                                color: {
                                    type: 'linear',
                                    x: 0, y: 0, x2: 0, y2: 1,
                                    colorStops: [{
                                        offset: 0, color: 'rgba(120, 196, 212, 0.5)'
                                    }, {
                                        offset: 1, color: 'rgba(120, 196, 212, 0.1)'
                                    }]
                                }
                            }
                        }]
                    });

                    // 设置湿度图表
                    humidityChart.setOption({
                        title: { text: `${city} - 湿度变化趋势 (%)` },
                        tooltip: {
                            trigger: 'axis',
                            formatter: function(params) {
                                const item = data[params[0].dataIndex];
                                return `
                                    ${item.date} ${item.time}<br/>
                                    温度: ${item.temperature}°C<br/>
                                    湿度: ${item.humidity}%<br/>
                                    风速: ${item.wind_speed}m/s
                                `;
                            }
                        },
                        grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
                        xAxis: {
                            type: 'category',
                            data: dateTimes,
                            axisLabel: {
                                rotate: 45,
                                formatter: function(value) {
                                    return value.split(' ')[0];
                                }
                            }
                        },
                        yAxis: { type: 'value', name: '湿度 (%)' },
                        series: [{
                            name: '湿度',
                            type: 'line',
                            data: humidities,
                            smooth: true,
                            symbol: 'circle',
                            symbolSize: 8,
                            lineStyle: { width: 3, color: '#f2789f' },
                            itemStyle: { color: '#f2789f' },
                            areaStyle: {
                                color: {
                                    type: 'linear',
                                    x: 0, y: 0, x2: 0, y2: 1,
                                    colorStops: [{
                                        offset: 0, color: 'rgba(242, 120, 159, 0.5)'
                                    }, {
                                        offset: 1, color: 'rgba(242, 120, 159, 0.1)'
                                    }]
                                }
                            }
                        }]
                    });

                    // 隐藏加载状态
                    tempChart.hideLoading();
                    humidityChart.hideLoading();
                })
                .catch(error => {
                    console.error('获取数据失败:', error);

                    // 隐藏加载状态
                    tempChart.hideLoading();
                    humidityChart.hideLoading();

                    // 显示错误信息
                    tempChart.setOption({
                        title: { text: '数据加载失败' },
                        graphic: {
                            type: 'text',
                            left: 'center',
                            top: 'middle',
                            style: {
                                text: `数据加载失败: ${error.message || '未知错误'}`,
                                fontSize: 16,
                                fill: '#ccc'
                            }
                        }
                    });

                    humidityChart.setOption({
                        title: { text: '数据加载失败' },
                        graphic: {
                            type: 'text',
                            left: 'center',
                            top: 'middle',
                            style: {
                                text: `数据加载失败: ${error.message || '未知错误'}`,
                                fontSize: 16,
                                fill: '#ccc'
                            }
                        }
                    });
                })
                .finally(() => {
                    // 窗口大小变化时重绘图表
                    window.addEventListener('resize', function() {
                        tempChart.resize();
                        humidityChart.resize();
                    });
                });
        }
    </script>
</body>
</html>